<template>
<!--
多文件分块上传
-->
  <el-upload
      class="upload-demo"
      drag
      :multiple="true"
      :http-request="getFile"
      :on-remove="removeFile"
  >
    <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
    <div class="el-upload__text">
      Drop file here or <em>click to upload</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 500kb
      </div>
    </template>
  </el-upload>
  <el-button type="primary" @click="uploadFile(this.allFile)">上传</el-button>
</template>

<script >
import  {UploadFilled}  from '@element-plus/icons-vue'
import {uploadFile} from "@/axios";
import { ElMessage } from 'element-plus'

export default {
  name:"FileUpload",
  components:{
    UploadFilled
  },
  data(){
    return{
      allFile:[],
      fileUid:[],
      number:0,
      fileSize:0,
      fileData:{
        fileName:"",//文件名字
        chunk:null,//文件块
        fileChunk:0,//文件块数
        ChunkNumber:0//第几块
      }

    }
  },
  methods:{
    getFile(option){
      this.allFile.push(option)
      this.fileUid.push(option.file.uid )
    },
    removeFile(option){
      console.log(this.fileUid)
      console.log(option.uid)
      var index = this.fileUid.map(item => item).indexOf(option.uid)
      console.log(index)
      this.allFile.splice(index,1)
      this.fileUid.splice(index,1)
      console.log("最终版本：：")
      console.log(this.allFile)

    },
    uploadFile(option) {
      this.number = option.length
      if (this.number == 0){
        ElMessage({
          message: '你还没有上传文件',
          type: 'warning',
        })
      }
      for (let j = 0; j < this.number; j++) {
      this.fileData.fileName = option[j].file.name
      this.fileSize = option[j].file.size
      const chunkSize = 1024 * 1024//1MB
      this.fileData.fileChunk = Math.ceil(this.fileSize / chunkSize)
      for (let i = 0; i < this.fileData.fileChunk; i++) {
        console.log("上传次数::::" + i + 1)
        const start = i * chunkSize
        const end = Math.min(this.fileSize, start + chunkSize)
        this.fileData.chunk = option[j].file.slice(start, end)
        // const chunk = option.file.slice(start,end)
        this.fileData.ChunkNumber = i + 1
        const formData = new FormData()
        formData.append("file", this.fileData.chunk)
        formData.append("fileName", this.fileData.fileName)
        formData.append("chunkNumber", i + 1)
        formData.append('totalChunks', this.fileData.fileChunk)
        uploadFile(formData)
      }
    }
      if (this.number!=0){
        ElMessage({
          message: '成功上传',
          type: 'success',
        })
      }

    }
  }
}
</script>

<style scoped>

</style>
